/**
 * @param {number[][]} grid
 * @return {number}
 */
var maxDistance = function (grid) {
    const len = grid.length
    const queue = []
    for (let i = 0; i < len; i++) {
        for (let j = 0; j < len; j++) {
            if (grid[i][j] === 1) {
                queue.push([i, j, 0])
            }
        }
    }
    if (queue.length === 0 || queue.length === len * len) {
        return -1
    }
    let p = null
    while (queue.length > 0) {
        p = queue.shift()
        const [x, y, deep] = p
        if (x + 1 < grid.length && grid[x + 1][y] == 0) {
            grid[x + 1][y] = 1;
            queue.push([x + 1, y, deep + 1])
        }
        if (x - 1 >= 0 && grid[x - 1][y] == 0) {
            grid[x - 1][y] = 1;
            queue.push([x - 1, y, deep + 1])
        }
        if (y + 1 < grid[0].length && grid[x][y + 1] == 0) {
            grid[x][y + 1] = 1;
            queue.push([x, y + 1, deep + 1])
        }
        if (y - 1 >= 0 && grid[x][y - 1] == 0) {
            grid[x][y - 1] = 1;
            queue.push([x, y - 1, deep + 1])
        }
    }
    return p[2]
};